#pragma once

#include <iostream>
#include <cstring>
#include <unistd.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "Log.hpp"

#define BACKLOG 5

class TcpServer
{
private:
    int _port;//监听端口
    int _listen_sock;//监听套接字
    static TcpServer* _tcp;//单例模式
private:
    TcpServer(int port)
        :_port(port)
        ,_listen_sock(-1)
    {}
    TcpServer(const TcpServer&) = delete;
    TcpServer& operator=(const TcpServer&) = delete;

public:
    static TcpServer* GetInstance(int port)
    {
        static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;//静态互斥锁
        if(_tcp==nullptr)
        {
            pthread_mutex_lock(&mutex);//加锁
            if(_tcp==nullptr)
            {
                _tcp = new TcpServer(port);
                _tcp->InitServer();
            }
            pthread_mutex_unlock(&mutex);//解锁
        }
        return _tcp;
    }
    void InitServer()
    {
        Socet();
        Bind();
        Listen();
        LOG(INFO,"TcpServer init success");
    }
    void Socet()
    {
        _listen_sock = socket(AF_INET,SOCK_STREAM,0);
        if(_listen_sock<0)
        {
            LOG(FATAL,"socket error");
            exit(1);
        }
        int opt=1;
        setsockopt(_listen_sock,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));
        LOG(INFO,"create socket success");
    }
    void Bind()
    {
        struct sockaddr_in addr;
        addr.sin_family = AF_INET;
        addr.sin_port = htons(_port);
        addr.sin_addr.s_addr = htonl(INADDR_ANY);
        if(bind(_listen_sock,(struct sockaddr*)&addr,sizeof(addr))<0)
        {
            LOG(FATAL,"bind error");
            exit(2);
        }
        LOG(INFO,"bind success");
    }
    void Listen()
    {
        if(listen(_listen_sock,BACKLOG)<0)
        {
            LOG(FATAL,"listen error");
            exit(3);
        }
        LOG(INFO,"listen success");
    }
    int Sock()
    {
        return _listen_sock;
    }
    ~TcpServer()
    {
        if(_listen_sock>=0)
        {
            close(_listen_sock);
        }
    }
};

TcpServer* TcpServer::_tcp = nullptr;